import React, { useState } from "react";
import { Toast, Form, Button, Input, NavBar } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import { getLogin } from "../../api/info"; 
import { useDispatch } from "react-redux";
import { setUser } from "../../store/Slice/userSlice";
function Login() {
  let nav = useNavigate();
  let [flag, setFlag] = useState(true);
  let [form] = Form.useForm();
  let dis = useDispatch();
  const mm = () => {
    let m = form.validateFields(["password"]);
    if (m.length !== 0) {
      setFlag(false);
    }
  };
  const onFinish = async (values) => {
    console.log(values);
    let { data: res } = await getLogin(values);
    Toast.show({
      icon: "success",
      content: "登录成功",
    });
    dis(setUser(res));
    nav("/");
  };
  return (
    <div>
      <NavBar onBack={() => nav(-1)} />
      <h1
        style={{
          textAlign: "center",
          padding: "100px 20px 10px",
          fontWeight: "normal",
        }}
      >
        登录
      </h1>
      <Form
        form={form}
        onFinish={onFinish}
        style={{
          padding: "15px",
          "--border-bottom": "none",
          "--border-top": "none",
          "--prefix-width": "75px",
        }}
        layout="horizontal"
        footer={
          <Button
            disabled={flag}
            block
            type="submit"
            color="danger"
            size="large"
            shape="rounded"
          >
            登录
          </Button>
        }
      >
        <Form.Item
          name="username"
          style={{
            background: "#f5f5f5",
            borderRadius: "10px",
            marginBottom: "30px",
          }}
          rules={[
            { required: true, message: "电子邮箱不能为空" },
            {
              pattern: /^\d{3,8}@(163.com||qq.com)$/,
              message: "网易邮箱或qq邮箱",
            },
          ]}
        >
          <Input placeholder="输入你的电子邮箱" />
        </Form.Item>
        <Form.Item
          style={{ background: "#f5f5f5", borderRadius: "10px" }}
          name="password"
          rules={[{ required: true, message: "密码不能为空" }]}
        >
          <Input onChange={mm} placeholder="输入您的密码" />
        </Form.Item>
        <p style={{ textAlign: "right", color: "gray", margin: "10px" }}>
          忘记密码了吗？
        </p>
      </Form>
      <p style={{ textAlign: "center", color: "gray" }}>
        没有账户？<span style={{ color: "#000" }}>立即注册</span>
      </p>
    </div>
  );
}

export default Login;
